package com.glorystone.ins.controller;

import com.alibaba.fastjson.JSON;
import com.glorystone.ins.common.JsonResult;
import com.glorystone.ins.domain.Advance;
import com.glorystone.ins.domain.BusinessLog;
import com.glorystone.ins.domain.SysUser;
import com.glorystone.ins.enums.FlowBusinessTypeEnum;
import com.glorystone.ins.enums.FlowOperateTypeEnum;
import com.glorystone.ins.enums.WorkFlowEnum;
import com.glorystone.ins.service.AdvanceService;
import com.glorystone.ins.service.AuditTaskService;
import com.glorystone.ins.service.BusinessLogService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author:haoguodong
 * @Date:Created in 10:20 2018/3/17
 */
@Slf4j
@Controller
@RequestMapping("/advance")
public class AdvanceController extends BaseController {

    @Autowired
    private AdvanceService advanceService;

    @Autowired
    private AuditTaskService auditTaskService;

    @Autowired
    private BusinessLogService businessLogService;

    /**
     * 垫资页面
     */
    @RequestMapping(value = "toList",method = RequestMethod.GET)
    public String toAdvanceView(Model model){
        //查询数据库
        List<Advance> list=advanceService.findAdvanceAmt();
       /* Advance advance=new Advance();*/
       /* if(list.size()==0){
             advance.setAuditStatus(Advance.AuditStatusEnum.CHECK_SUCCESS.getValue());
             advance.setTodatAmount(BigDecimal.valueOf(123));
             advance.setStatus(1);
             advance.setDelFlg(Advance.DeleteFlagEnum.DELETED.getValue());
             advanceService.insertTodatAmount(advance);
         }else{
            advance=list.get(0);
        }*/
       /* for(Advance ad : list){
            ad.setTodatAmount(ad.getTodatAmount().divide(new BigDecimal(1000)));
        }*/
        /*Advance advance=list.get(0);*/
        Advance advance=new Advance();
        advance.setTodatAmount(list.get(0).getTodatAmount().divide(new BigDecimal(10000)));
        model.addAttribute("advance",advance);

        return "advance/advance_list";
    }

    /**
     * 设置垫资限额
     */
   @RequiresPermissions(value = "advance:amount:edit")
   @RequestMapping(value = "udpateAdvanceAmtount")
   @ResponseBody
   public Boolean updateAdvanceAmt(HttpServletRequest request) {
       SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
       String applyAmount = request.getParameter("applyAmount");

       Advance advance = new Advance();
       advance.setApplyAmount(new BigDecimal(applyAmount).multiply(new BigDecimal(10000)));
       advance.setDelFlg(Advance.DeleteFlagEnum.NORMAL.getValue());
       advance.setCreateBy(user.getTid());
       advance.setCreateAt(LocalDateTime.now());
       advance.setAuditStatus(Advance.AuditStatusEnum.CHECK_FIRST.getValue());
       List<Advance> list = advanceService.findSuccessStatus();

       if (list.size() == 0) {
           advanceService.insertApply(advance);
           businessLogService.save(BusinessLog.BusinessTypeEnum.ADVANCE_LIMIT, advance.getTid(), BusinessLog.ContentEnum.SET_ADVANCE_AMOUNT, null);
           //垫资金额设置完,调用审批接口
           auditTaskService.submit(WorkFlowEnum.ADVANCE_LIMIT, FlowBusinessTypeEnum.ADVANCE_LIMIT, advance.getTid(), FlowOperateTypeEnum.START);
           return true;
       } else {
           return false;
       }

   }
    /**
     * 垫资审核页面
     */
    @RequestMapping(value = "chenckAdvance",method = RequestMethod.GET)
    public String checkAdvanceInfo(Model model,Long tid,String t){
        log.info("-------传入参数垫资tid:"+tid);
        List<Advance> advanceList = advanceService.findAdvanceList();
        Advance advance = advanceService.findAdvanceOne(tid);
        List<BusinessLog> businessLogList=businessLogService.findList(BusinessLog.BusinessTypeEnum.ADVANCE_LIMIT,tid);
        model.addAttribute("advance",advance);
        model.addAttribute("advanceList",advanceList);
        model.addAttribute("role",t);
        model.addAttribute("businessLogList",businessLogList);
        return "advance/advanceInfo";
    }

    /**
     * 业务负责人审核
     */
    @RequestMapping(value="checkAdvanceByBusiness",method = RequestMethod.POST)
    @ResponseBody
    public Boolean checkAdvanceByBusiness(Advance advance,String remark){
        log.info("----------------传入参数advance:"+advance+"--------------------------");
        Boolean flag = false;
        try{
            advanceService.checkAdvance(advance);
           businessLogService.save(BusinessLog.BusinessTypeEnum.ADVANCE_LIMIT,advance.getTid(),BusinessLog.ContentEnum.ADVANCE_CHECK_PASS,remark);
           auditTaskService.submit(WorkFlowEnum.ADVANCE_LIMIT,FlowBusinessTypeEnum.ADVANCE_LIMIT,advance.getTid(),FlowOperateTypeEnum.PASS);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 财务经理审核
     */
    @RequestMapping(value = "checkAdvanceByFinance",method = RequestMethod.POST)
    @ResponseBody
    public Boolean checkAdvanceByFinance(Advance advance,String remark){
        log.info("----------------传入参数advance:"+advance+"--------------------------");
        Boolean flag = false;
        try {
            advanceService.checkAdvances(advance);
            businessLogService.save(BusinessLog.BusinessTypeEnum.ADVANCE_LIMIT,advance.getTid(),BusinessLog.ContentEnum.ADVANCE_CHECK_PASS,remark);
            auditTaskService.submit(WorkFlowEnum.ADVANCE_LIMIT,FlowBusinessTypeEnum.ADVANCE_LIMIT,advance.getTid(),FlowOperateTypeEnum.PASS);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 审核驳回
     */
    @RequestMapping(value ="/rejectAdvance",method = RequestMethod.POST)
    @ResponseBody
    public Boolean rejectAdvance(Advance advance,String remark) {
        log.info("----------------传入参数advance:" + advance + "--------------------------");
        Boolean flag = false;
        try {
            advanceService.rejectAdvance(advance);
            businessLogService.save(BusinessLog.BusinessTypeEnum.ADVANCE_LIMIT, advance.getTid(), BusinessLog.ContentEnum.ADVANCE_CHECK_REJECT, remark);
            auditTaskService.submit(WorkFlowEnum.ADVANCE_LIMIT, FlowBusinessTypeEnum.ADVANCE_LIMIT, advance.getTid(), FlowOperateTypeEnum.REJECT);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 图表数据
     */
    @RequestMapping(value = "chartData")
    @ResponseBody
    public String chartData(@RequestParam(value="type") String type){
        List<Advance> advanceList = null;
        List<Map<String,String>> result = Lists.newArrayList();
        try {
            if (type != null) {
                advanceList = advanceService.getAdvanceList(type);
                for(Advance ad : advanceList){
                    Map<String,String> map = Maps.newHashMap();
                    LocalDateTime lt= ad.getCreateAt();
                    map.put("history",""+ad.getTodatAmount());
                    if(ad.getActualAmount()==null){
                        map.put("actual",""+0);
                    }else {
                        map.put("actual",""+ad.getActualAmount());
                    }
                    map.put("day",lt.getYear()+"-"+lt.getMonthValue()+"-"+lt.getDayOfMonth());
                    result.add(map);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.print(JSON.toJSONString(result));
        return JSON.toJSONString(result);

    }


}
